package itbour.onetouchshow.activity.video.videopreview;

import android.os.Environment;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.google.gson.Gson;
import com.lsjr.callback.DownloadSubscriber;
import com.lsjr.callback.EncryBeanCallBack;
import com.lsjr.utils.HttpUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import itbour.onetouchshow.App;
import itbour.onetouchshow.AppCache;
import itbour.onetouchshow.activity.version1_4.V1_4_VideoPreviewActivity;
import itbour.onetouchshow.base.mvp.BasePresenterImpl;
import itbour.onetouchshow.bean.DownloadVideoBean;
import itbour.onetouchshow.bean.UserDetailInfoBean;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.AlbumNotifyHelper;
import itbour.onetouchshow.utils.DateUtils;
import itbour.onetouchshow.utils.FileUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class VideoPreviewPresenter extends BasePresenterImpl<VideoPreviewContract.View> implements VideoPreviewContract.Presenter {

    /**
     * 提供取消
     */
    public OSSAsyncTask task;
    V1_4_VideoPreviewActivity v1_4_videoPreviewActivity;

    public VideoPreviewPresenter(VideoPreviewContract.View view) {
        mvpView = view;
    }

    public void setV1_4_videoPreviewActivity(V1_4_VideoPreviewActivity v1_4_videoPreviewActivity) {
        this.v1_4_videoPreviewActivity = v1_4_videoPreviewActivity;
    }

    public void loadVideoUserDocBg(String docId) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        stringObjectHashMap.put("pageNum", 0);
        stringObjectHashMap.put("pageSize", AppConst.PAGE_SIZE);
        HttpUtils.getInstance().executeGet(AppConfig.GETVIDEOUSERDOCBGLIST_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                T_.showToastReal(exception);
            }

            @Override
            protected void onSuccess(String response) {
                if (mvpView != null) {
                    mvpView.loadVideoUserDocBgSucceed(response);
                }

                //L_.e(response);
            }
        });
    }

    /**
     * 点击切换背景先设置背景
     * <p>
     * 在获取作品预览
     */
    public void loadSetVideoBg(String docId, String bgId) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        stringObjectHashMap.put("bgId", bgId);
        HttpUtils.getInstance().executeGet(AppConfig.SETVIDEOBG_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {

            }

            @Override
            protected void onSuccess(String response) {
                /*获取作品预览 */
                loadDocPreview(docId);
            }
        });
    }

    /*
   * 作品预览
   * */
    public void loadDocPreview(String docId) {
        L_.e("作品预览" + docId);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        HttpUtils.getInstance().executeGet(AppConfig.GETDOCPREVIEW_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                T_.showCustomToast(exception);
                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
            }

            @Override
            protected void onSuccess(String response) {
                if (mvpView != null) {
                    L_.e(response);
                    //mvpView.loadDocPreviewSuccess(response);
                }
            }
        });
    }

    /**
     * 作品预览  new
     */
    public void newLoadDocPreview(String docId) {
        L_.e("作品预览" + docId);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        HttpUtils.getInstance().executePost(AppConfig.REQUESTUSERDOCPRIVEWINFO_WEB_V1_1, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                T_.showCustomToast(exception);
                L_.e("newLoadDocPreview" + exception);
                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
            }

            @Override
            protected void onSuccess(String response) {
                if (mvpView != null) {
                    L_.e("newLoadDocPreview" + response);
                    mvpView.loadNewDocPreviewSuccess(response);
                }
            }
        });
    }

    /**
     * 刷新个人秀米数据
     */
    public void loadUserDetailInfo() {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        HttpUtils.getInstance().executeGet(AppConfig.GETUSERDETAILINFO_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                L_.e(exception);
                T_.showCustomToast(exception);
            }

            @Override
            protected void onSuccess(String response) {
                UserDetailInfoBean userDetailInfoBean = new Gson().fromJson(response, UserDetailInfoBean.class);
                if (userDetailInfoBean == null) {
                    return;
                }
                App.setIntegral(Integer.parseInt(userDetailInfoBean.getUserInfo().getWallet().getPointBalance() == null ? "-1" : userDetailInfoBean.getUserInfo().getWallet().getPointBalance()));
                App.setUserDetailInfoBean(userDetailInfoBean);
            }
        });
    }

    /**
     * 作品预览
     */
    public void showFromStaus(String docId) {
        L_.e("作品预览" + docId);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        HttpUtils.getInstance().executeGet(AppConfig.GETDOCPREVIEW_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }

            }

            @Override
            protected void onSuccess(String response) {
                if (mvpView != null) {
                    mvpView.showFromStaus(response);
                }

                L_.e(response);
            }
        });
    }

    public void removeWatermark(String docId) {
        //L_.e(App.getLoginBean().getUserInfo().getUserId() + "");
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        HttpUtils.getInstance().executeGet(AppConfig.REMOVEWATERMARK_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                T_.showCustomToast("去水印失败");

                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
                L_.e(exception);
            }

            @Override
            protected void onSuccess(String response) {

                L_.e("response" + response);
                if (mvpView != null) {
                    //   mvpView.loadDocPreview(response);
                    mvpView.removeWaterLoadDocPreview(response);
                }

                //mvpView.removeWaterLoadDocPreview(response);
            }
        });

    }

    public void deleteVideoBg(String docId) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", 610);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        HttpUtils.getInstance().executeGet(AppConfig.CLEARVIDEOBG_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                L_.e(exception);
                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
            }

            @Override
            protected void onSuccess(String response) {

                if (mvpView != null) {
                    mvpView.deleteVideoBgSuccess(response);
                }
                // L_.e("response" + response);

                //mvpView.removeWaterLoadDocPreview(response);
            }
        });
    }

    /**
     * 1. 下载视频带背景(若有背景), 2 仅下载小视频,
     *
     * @param docId
     * @param downLoadType
     */
    public void getDownVideoUrl(String docId, int downLoadType) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", 610);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        stringObjectHashMap.put("downloadType", downLoadType);
        HttpUtils.getInstance().executeGet(AppConfig.GETDOCDOWNLOADURL_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                T_.showToastReal(exception);
                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
            }

            @Override
            protected void onSuccess(String response) {
                L_.e("response" + response);
                DownloadVideoBean downloadVideoBean = new Gson().fromJson(response, DownloadVideoBean.class);
                doDonwload(downloadVideoBean.getDownloadUrls().get(0));
                //oosDownload(downloadVideoBean.getDownloadUrls().get(0));

               /*
               * response{"downloadUrls":
               * ["http://itbour-generate.itbour.com/video/U299486/2017/12/14/212552705_wA1raO87Rlw5wceagVZl/0.mp4"],
               * "fileSize":388367,"docId":2228,"opType":2}
               * */
                // mvpView.deleteVideoBgSuccess(response);
                //mvpView.removeWaterLoadDocPreview(response);
            }
        });
    }

    public void getDownVideoUrl(String docId) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", 610);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        HttpUtils.getInstance().executeGet(AppConfig.GETDOCDOWNLOADURL_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                T_.showToastReal(exception);
                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
            }

            @Override
            protected void onSuccess(String response) {
                L_.e("response" + response);
                DownloadVideoBean downloadVideoBean = new Gson().fromJson(response, DownloadVideoBean.class);
                doDonwload(downloadVideoBean.getDownloadUrls().get(0));
                //oosDownload(downloadVideoBean.getDownloadUrls().get(0));

               /*
               * response{"downloadUrls":
               * ["http://itbour-generate.itbour.com/video/U299486/2017/12/14/212552705_wA1raO87Rlw5wceagVZl/0.mp4"],
               * "fileSize":388367,"docId":2228,"opType":2}
               * */
                // mvpView.deleteVideoBgSuccess(response);
                //mvpView.removeWaterLoadDocPreview(response);
            }
        });
    }

    public void doDonwload(String url) {
        // File outputfile = new File(UIUtils.getContext().getExternalCacheDir(), "output.mp4");

        String name = DateUtils.getYMD() + FileUtils.getFileName(url);
        //先查找本地   必须保证在我们自己的目录下打开才能找到  如果自己发出相当于重新下载一次
        boolean downLoad = true;
        String path = Environment.getExternalStorageDirectory() + "/OneTouchShow";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        if (AppCache.getInstance().fileExists(path, name)) {
            downLoad = false;
        }
        if (downLoad) {
            L_.e("下载文件" + name);
            HttpUtils.getInstance().downloadFile(url, new DownloadSubscriber(UIUtils.getContext(),
                    null, name) {
                @Override
                public void onComplete(String path) {
                    L_.e("文件保存路径：" + path);
                    T_.showCustomToast("文件保存路径：" + path);
                    AlbumNotifyHelper.insertVideoToMediaStore(UIUtils.getContext(), String.valueOf(System.currentTimeMillis()), 0, 0);
                    //AlbumNotifyHelper.insertImageToMediaStore(UIUtils.getContext(), path, System.currentTimeMillis());
                    if (mvpView != null) {
                        mvpView.downLoadVideoSuccess(path);
                    }

                }

                @Override
                public void update(long bytesRead, long contentLength, boolean done) {
                    int progress = (int) (bytesRead * 100 / contentLength);
                    L_.e(progress + "% ");
                }

                @Override
                protected void onXError(String exception) {
                    L_.e(exception + "% ");
                    T_.showToastReal(exception);
                    if (mvpView != null) {
                        mvpView.loadFaild(exception);
                    }
                }
            });
        } else {
            path = path + File.separator + name;
            path = path.replaceAll("//", "/");
            if (mvpView != null) {
                mvpView.downLoadVideoSuccess(path);
            }
        }

    }

    /**
     * 1. 下载视频带背景(若有背景), 2 仅下载小视频,
     *
     * @param docId
     * @param downLoadType
     */
    public void downLoadForAliOss(String docId, int downLoadType) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        stringObjectHashMap.put("downloadType", downLoadType);
        HttpUtils.getInstance().executeGet(AppConfig.GETDOCDOWNLOADURL_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                T_.showToastReal(exception);
                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
            }

            @Override
            protected void onSuccess(String response) {
                L_.e("response" + response);


                if (mvpView != null) {
                    mvpView.getDownloadUrl(response);
                }

            }
        });
    }

    public void alidownLoadFile(String videoUrl) {
        L_.e(videoUrl);
        //  String url="http://itbour-generate.itbour.com/video/U25/2018/03/29/114530009_wtIedfgAqiYG1TJmHWFM/0.mp4";
        String path = Environment.getExternalStorageDirectory() + "/OneTouchShow";
        L_.e(path);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String name = DateUtils.getYMD() + FileUtils.getFileName(videoUrl);
        path = path + File.separator + name;
        path = path.replaceAll("//", "/");
        File futureStudioIconFile = new File(path);

        L_.e(futureStudioIconFile.getAbsolutePath() + "文件绝对路径");

        String key = videoUrl.replace("http://itbour-generate.itbour.com/", "");
        //  http://itbour-generate.itbour.com/
        GetObjectRequest get = new GetObjectRequest(AppConst.OSSDOWNBUCKETNAME, key);//设置下载进度回调
        //设置下载进度回调
        String finalPath = path;
        get.setProgressListener(new OSSProgressCallback<GetObjectRequest>() {
            @Override
            public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
                OSSLog.logDebug("getobj_progress: " + currentSize + "  total_size: " + totalSize, false);
                L_.e("getobj_progress: " + currentSize + "  total_size: " + totalSize);
                L_.e("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (currentSize * 100 / totalSize);
                L_.e(progress + "% ");
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        v1_4_videoPreviewActivity.oneToucDialog.setTvprogress(progress + "% ");
                        v1_4_videoPreviewActivity.oneToucDialog.setDownloadProgress(progress);
                        if (progress >= 100) {
                            v1_4_videoPreviewActivity.oneToucDialog.dismiss();
                            if (mvpView != null) {
                                mvpView.downLoadVideoSuccess(finalPath);
                            }
                        }
                    }
                });

            }
        });
        task = App.ossClient.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {

                FileOutputStream outputStream = null;
                // 请求成功
                InputStream inputStream = result.getObjectContent();
                byte[] fileReader = new byte[1024];
                int fileSizeDownloaded = 0;
                try {
                    outputStream = new FileOutputStream(futureStudioIconFile);
                    while ((fileSizeDownloaded = inputStream.read(fileReader)) != -1) {
                        // 处理下载的数据
                        outputStream.flush();
                        outputStream.write(fileReader, 0, fileSizeDownloaded);
                    }

                    if (outputStream != null) {
                        outputStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    Observable.just(finalPath).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
                        public void call(String aLong) {
                            // DownloadSubscriber.this.onComplete(path);
                            T_.showToastReal("下载成功" + finalPath);

                        }
                    });
                    if (finalPath.contains(".mp4")) {
                        AlbumNotifyHelper.insertVideoToMediaStore(UIUtils.getContext(), String.valueOf(System.currentTimeMillis()), 0, 0);
                        DownloadSubscriber.insertIntoMediaStore(UIUtils.getContext(), true, futureStudioIconFile, 0L);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        //取消
        // task.cancel();

    }

    /**
     * 获取作品数据
     */
    public void getDocString(String docId) {
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        //  L_.e(videoBean.getId() + "");
        stringStringHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringStringHashMap.put("id", docId);
        stringStringHashMap.put("userId", App.getUserId());
        stringStringHashMap.put("isTmpl", 0);
        HttpUtils.getInstance().executeGet(AppConfig.GET_DOC_CONTENT_V10, stringStringHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                L_.e(exception);
                T_.showToastReal(exception);
                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
            }

            @Override
            protected void onSuccess(String response) {

                if (mvpView != null) {
                    mvpView.getDocStringPreview(response);
                }

            }
        });

    }


    /*
  获取作品数据
  * */
    public void getCopyDocStringAndNew(String docId) {
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        //  L_.e(videoBean.getId() + "");
        stringStringHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringStringHashMap.put("docId", docId);
        stringStringHashMap.put("userId", App.getUserId());
        HttpUtils.getInstance().executeGet(AppConfig.GETUSERDOCCOPYTMPL_V1_0, stringStringHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                L_.e(exception);
                T_.showToastReal(exception);

                if (mvpView != null) {
                    mvpView.loadFaild(exception);
                }
            }

            @Override
            protected void onSuccess(String response) {

                if (mvpView != null) {
                    mvpView.copyAndNewProductSuccess(response);
                }


            }
        });

    }


    public void doReNameWork(String docId, String name) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        stringObjectHashMap.put("name", name);
        HttpUtils.getInstance().executeGet(AppConfig.RENAMEUSERDOC_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                L_.e(exception);
                T_.showCustomToast(exception);
            }

            @Override
            protected void onSuccess(String response) {
                L_.e(response);
            }
        });
    }


}
